<template>
  <div class="setting-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 左侧 -->
          <el-tab-pane label="角色管理">
            <!-- 按钮 -->
            <el-button icon="el-icon-plus" size="small" type="primary" @click="isShowAddBox=true">新增角色</el-button>
            <!-- 表格 -->
            <el-table v-loading="loading" :data="list">
              <el-table-column type="index" :index="handleIndex" label="序号" width="100" />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label=" 操作">
                <template v-slot="{row}">
                  <el-button size="small" type="success" @click="giveRole(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="handleEdit(row.id)">编辑</el-button>
                  <el-button size="small" type="danger" @click="delRole(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination :page-sizes="[3, 20, 30, 40, 50, 100]" layout="sizes, prev, pager, next, jumper, ->, total" :total="total" :current-page="queryParams.page" :page-size="queryParams.pagesize" @current-change="changePage" @size-change="sizeChange" />
            <el-tab-pane label="公司信息">
              <!-- 公司信息 -->
            </el-tab-pane>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
    <el-dialog :title="title" :visible.sync="isShowAddBox" @close="btnCancel">
      <el-form ref="roleForm" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入角色描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="btnCancel">取消</el-button>
        <el-button type="primary" @click="handleAdd">确认</el-button>
      </template>
    </el-dialog>
    <!-- 分配权限的弹层 -->
    <el-dialog title="分配权限" :visible.sync="showAuthDialog" @open="loadPermList">
      <el-tree ref="myTree" :data="permissions" show-checkbox node-key="id" :default-expand-all="true" :default-checked-keys="defaultAuthList" :props="defaultProps" />
      <template #footer>
        <div style="text-align: right;">
          <el-button @click="showAuthDialog=false">取消</el-button>
          <el-button type="primary" @click="handleAuth">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { reqGetRoleList, reqDeleteRole, reqAddRole, reqUpdateRole, reqGetRoleDetail, reqAssignPerm } from '../../api/settings'
import { reqGetPermissionList } from '../../api/permission'
import { tranlateListToTree } from '../../utils/index'
export default {
  data () {
    return {
      // 设置自己有的默认权限高亮勾选
      defaultAuthList: [],
      // 设置树形节点信息
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      // 权限列表
      permissions: [],
      roleId: '',
      showAuthDialog: false,
      isShowAddBox: false,
      // 查询参数
      queryParams: {
        page: 1,
        pagesize: 3
      },
      list: [],
      total: 0,
      loading: false,
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  computed: {
    // 控制弹出表单标题是编辑还是添加
    title () {
      return this.form.id ? '编辑角色' : '添加角色'
    }
  },
  created () {
    this.loadRoleList()
  },
  methods: {
    // 动态生成索引
    handleIndex (index) {
      const { page, pagesize } = this.queryParams
      return (page - 1) * pagesize + index + 1
    },
    // 监听每页条数的变化
    sizeChange (pagesize) {
      this.queryParams.pagesize = pagesize
      this.loadRoleList()
    },
    changePage (page) {
      this.queryParams.page = page
      this.loadRoleList()
    },
    async loadRoleList () {
      try {
        this.loading = true
        const ret = await reqGetRoleList(this.queryParams)
        this.list = ret.data.rows
        this.total = ret.data.total
      } catch {
        this.$emit.error('查询失败!')
      } finally {
        this.loading = false
      }
    },
    async delRole (id) {
      try {
        const ret = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        if (ret === 'cancel') return
        const result = await reqDeleteRole(id)
        if (result.code === 10000) {
          this.loadRoleList()
          this.$message.success('删除成功')
        } else {
          this.$message.error(result.message)
        }
      } catch {
        this.$message.error('删除失败')
      }
    },
    // 点击按钮添加角色
    handleAdd () {
      this.$refs.roleForm.validate(async validate => {
        if (!validate) return
        if (this.form.id) {
          try {
            const ret = await reqUpdateRole(this.form)
            if (ret.code === 10000) {
              // 添加成功：关闭弹窗；刷新列表；清空表单
              this.isShowAddBox = false
              this.loadRoleList()
              // reetFields方法依赖于el-form-item组件的prop属性
              this.$refs.roleForm.resetFields()
            }
          } catch {
            this.$message.error('添加角色失败')
          }
        } else {
          try {
            const ret = await reqAddRole(this.form)
            if (ret.code === 10000) {
              // 添加成功：关闭弹窗；刷新列表；清空表单
              this.isShowAddBox = false
              this.loadRoleList()
              // reetFields方法依赖于el-form-item组件的prop属性
              this.$refs.roleForm.resetFields()
            }
          } catch {
            this.$message.error('添加角色失败')
          }
        }
      })
    },
    btnCancel () {
      this.isShowAddBox = false
      this.$refs.roleForm.resetFields()
      this.form = {}
    },
    async handleEdit (id) {
      try {
        // 显示弹窗；获取角色数据
        this.isShowAddBox = true
        const ret = await reqGetRoleDetail(id)
        if (ret.code === 10000) {
          this.form = ret.data
        }
      } catch {
        this.$message.error('编辑失败!')
      }
    },
    giveRole (roleId) {
      this.showAuthDialog = true
      this.roleId = roleId
    },
    async loadPermList () {
      // 加载所有的权限
      const ret = reqGetPermissionList()
      // 加载角色本来拥有的权限列表
      const ret1 = reqGetRoleDetail(this.roleId)
      Promise.all([ret, ret1]).then(results => {
        this.permissions = tranlateListToTree(results[0].data, '0')
        this.defaultAuthList = results[1].data.permIds
      })
    },
    // 点击确定完成用户权限
    async handleAuth () {
      try {
        const ret = await reqAssignPerm({
          id: this.roleId,
          permIds: this.$refs.myTree.getCheckedKeys()
          // permIds: this.defaultAuthList
        })
        if (ret.code === 10000) {
          console.log('葫芦娃')
          this.showAuthDialog = false
          this.$message.success('授权成功!')
          this.permissions = []
          // this.setCheckedKeys([])
        }
      } catch (err) {
        this.$message.error('授权失败!')
      }
    }
  }
}
</script>

<style>
</style>
